package com.xiyu.service.service.mailbox;

import com.xiyu.service.enums.mailbox.mail.MailboxMailApproveStatusEnum;
import com.xiyu.service.enums.system.notice.SystemNoticeTypeEnum;
import com.xiyu.service.framework.postOffice.factory.PostOfficeFactory;
import com.xiyu.service.framework.postOffice.service.PostOfficeService;
import com.xiyu.service.model.mailbox.account.MailboxAccount;
import com.xiyu.service.model.mailbox.mail.MailboxMail;
import com.xiyu.service.model.mailbox.mail.MailboxMailApprove;
import com.xiyu.service.model.system.notice.SystemNotice;
import com.xiyu.service.model.system.notice.SystemNoticeDraft;
import com.xiyu.service.repository.mailbox.account.MailboxAccountRepository;
import com.xiyu.service.repository.mailbox.mail.MailboxMailApproveReceiverRepository;
import com.xiyu.service.repository.mailbox.mail.MailboxMailApproveRepository;
import com.xiyu.service.repository.mailbox.mail.MailboxMailRepository;
import com.xiyu.service.repository.system.notice.SystemNoticeRepository;
import com.xiyu.service.service.system.user.UserService;
import com.xiyu.service.vo.mailbox.mailApprove.MailApproveRevertInput;
import com.xiyu.service.vo.mailbox.mailApprove.MailApproveDoneInput;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import static com.xiyu.service.errorCode.mailbox.MailApproveErrorCode.MAILBOX_APPROVE_NOT_EXIST;
import static com.xiyu.service.errorCode.mailbox.MailApproveErrorCode.MAILBOX_APPROVE_STATUE_ERROR;
import static com.xiyu.service.errorCode.mailbox.MailErrorCode.*;
import static com.xiyu.service.framework.exception.util.ServiceExceptionUtil.exception;
import static com.xiyu.service.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * 邮件审批 Service 实现类
 */
@Service
@Validated
public class MailApproveServiceImpl implements MailApproveService {

    @Resource
    private MailboxMailApproveRepository mailboxMailApproveRepository;

    @Resource
    private MailboxMailApproveReceiverRepository mailboxMailApproveReceiverRepository;

    @Resource
    private MailboxAccountRepository mailboxAccountRepository;

    @Resource
    private MailboxMailRepository mailboxMailRepository;

    @Resource
    private PostOfficeFactory postOfficeFactory;

    @Resource
    private SystemNoticeRepository systemNoticeRepository;

    @Resource
    private UserService userService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean done(MailApproveDoneInput inputVO) {
        for(Long id : inputVO.getIds()){
            MailboxMailApprove approve = mailboxMailApproveRepository.findNullable(id);
            if(approve == null){
                throw exception(MAILBOX_APPROVE_NOT_EXIST);
            }
            if(!approve.status().equals(MailboxMailApproveStatusEnum.PENDING_APPROVAL.getValue())){
                throw exception(MAILBOX_APPROVE_STATUE_ERROR, MailboxMailApproveStatusEnum.PENDING_APPROVAL.getLabel());
            }
            MailboxMail mail = mailboxMailRepository.findNullable(approve.mailId());
            if(mail == null){
                throw exception(MAILBOX_MAIL_NOT_EXIST);
            }
            // 查找邮箱账号
            MailboxAccount account = mailboxAccountRepository.findNullable(mail.accountId());
            if(account == null){
                throw exception(MAILBOX_ACCOUNT_NOT_EXIST);
            }
            PostOfficeService postOfficeService = postOfficeFactory.getInstance(account.id());
            postOfficeService.sendMail(mail.id());
            postOfficeService.close();

            String nickName = userService.getUser(approve.creatorId()).orElse(null).nickname();
            SystemNotice notice = SystemNoticeDraft.$.produce(draft -> draft.setIsRead(false).setContent("您的邮件：" + mail.subject() + "-" +  nickName  +"审批通过，请知晓")
                    .setNotifierId(approve.creatorId()).setTitle("").setStatus(0).setType(SystemNoticeTypeEnum.MAIL.getValue()));
            systemNoticeRepository.insert(notice);
        }
        mailboxMailApproveRepository.updateStatus(inputVO.getIds(), MailboxMailApproveStatusEnum.DONE.getValue());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean revert(MailApproveRevertInput inputVO) {
        for(Long id : inputVO.getIds()){
            MailboxMailApprove approve = mailboxMailApproveRepository.findNullable(id);
            if(approve == null){
                throw exception(MAILBOX_APPROVE_NOT_EXIST);
            }
            if(!approve.status().equals(MailboxMailApproveStatusEnum.PENDING_APPROVAL.getValue())){
                throw exception(MAILBOX_APPROVE_STATUE_ERROR, MailboxMailApproveStatusEnum.PENDING_APPROVAL.getLabel());
            }
            MailboxMail mail = mailboxMailRepository.findNullable(approve.mailId());
            if(mail == null){
                throw exception(MAILBOX_MAIL_NOT_EXIST);
            }
            String nickName = userService.getUser(approve.creatorId()).orElse(null).nickname();
            SystemNotice notice = SystemNoticeDraft.$.produce(draft -> draft.setIsRead(false).setContent("您的邮件：" + mail.subject() + "-" +  nickName  +"审批驳回，请知晓")
                    .setNotifierId(approve.creatorId()).setTitle("").setStatus(0).setType(SystemNoticeTypeEnum.MAIL.getValue()));
            systemNoticeRepository.insert(notice);
        }
        mailboxMailApproveRepository.updateStatus(inputVO.getIds(), MailboxMailApproveStatusEnum.REVERT.getValue());
        return true;
    }

}
